﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using UIWindow.Lucifer;

namespace UIWindow.Domains
{
    public class Bootstrapper : INotifyPropertyChanged
    {
        /// <summary>
        /// UI线程上下文
        /// </summary>
        private static SynchronizationContext _uisContext { get; set; }
        private static IObjectContainer _objectContainer;
        public event PropertyChangedEventHandler PropertyChanged;
        private readonly static object _obj = new object();
        private static Bootstrapper _bootstrapper;
        public object ViewContext { get; set; }

        public static Bootstrapper Instance
        {
            get
            {
                if (_bootstrapper == null)
                {
                    lock (_obj)
                    {
                        if (_bootstrapper == null) _bootstrapper = new Bootstrapper();
                    }
                }
                return _bootstrapper;
            }
        }

        private Bootstrapper()
        {
            _objectContainer = new ObjectContainer();
            _uisContext = SynchronizationContext.Current;
        }

        public static IObjectContainer GetContainer() => _objectContainer;

#nullable enable
        /// <summary>
        /// 异步跨线程
        /// </summary>
        /// <param name="action"></param>
        /// <param name="para"></param>
        public static void UIAsync(SendOrPostCallback action, object? para) => _uisContext.Post(action, para);

        /// <summary>
        /// 同步跨线程
        /// </summary>
        /// <param name="action"></param>
        public static void UISynchronize(Action action) => Application.Current.Dispatcher.Invoke(action);
    }
}
